package com.sfpay.merchant.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfpay.merchant.auth.entity.system.SysDictData;
import com.sfpay.merchant.auth.mapper.SysDictDataMapper;
import com.sfpay.merchant.auth.service.ISysDictDataService;
import com.sfpay.merchant.auth.utils.DictUtils;
import com.sfpay.merchant.common.core.text.Convert;
import com.sfpay.merchant.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 字典数据表 服务实现类
 * </p>
 *
 * @author fangchen
 * @since 2022-08-17
 */
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements ISysDictDataService {

    @Autowired
    private SysDictDataMapper dictDataMapper;

    /**
     * 根据条件分页查询字典数据
     * @return 字典数据集合信息
     */
    @Override
    public String selectDictLabel(String dictType, String dictValue) {
        QueryWrapper<SysDictData> queryWrapper=new QueryWrapper();
        queryWrapper.lambda().eq(SysDictData::getDictType,dictType)
                             .eq(SysDictData::getDictValue,dictValue);
        SysDictData sysDictData=dictDataMapper.selectOne(queryWrapper);
        if(sysDictData!=null){
            return  sysDictData.getDictLabel();
        }
        return null;
    }

    @Override
    public List<SysDictData> selectDictDataList(SysDictData dictData) {
        return  dictDataMapper.selectDictDataList(dictData);
    }

    @Override
    public int insertDictData(SysDictData data) {
        int row = dictDataMapper.insertDictData(data);
        if (row > 0) {
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return row;
    }

    @Override
    public SysDictData selectDictDataById(Long dictCode) {
        return dictDataMapper.selectDictDataById(dictCode);
    }

    @Override
    public int updateDictData(SysDictData data) {
        int row = dictDataMapper.updateDictData(data);
        if (row > 0) {
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
        return row;
    }

    /**
     * 批量删除字典数据
     *
     * @param ids 需要删除的数据
     * @return 结果
     */
    @Override
    public void deleteDictDataByIds(String ids) {
        Long[] dictCodes = Convert.toLongArray(ids);
        for (Long dictCode : dictCodes) {
            SysDictData data = selectDictDataById(dictCode);
            dictDataMapper.deleteDictDataById(dictCode);
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
            DictUtils.setDictCache(data.getDictType(), dictDatas);
        }
    }
}
